<template>
  <dw-page-warpper>
    <div class="dw-condition-warpper">
      <el-form :inline="true" :model="searchFormData">
        <el-form-item label="关键字:">
          <el-input v-model="searchFormData.keyword" placeholder="请输入关键字或者拼音首字母进行搜索" clearable style="width: 320px" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="dw-toolbar-warpper">
      <el-button type="danger" @click="onDeleteList">批量删除</el-button>
    </div>
    <div class="dw-data-warpper">
      <el-table ref="loginLogTableRef" :data="tableData" border class="dw-full">
        <template #empty>
          <el-empty description="无数据"> </el-empty>
        </template>
        <el-table-column type="index" width="50" v-if="showRowNum" align="right" />
        <el-table-column type="selection" width="38" v-if="selection" />
        <el-table-column prop="loginCode" label="登录账号" width="160" />
        <el-table-column prop="ipAddress" label="IP地址" width="160" />
        <el-table-column prop="loginStatus" label="登录结果" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.loginStatus === 1" type="success" effect="dark">成功</el-tag>
            <el-tag v-else type="danger" effect="dark">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="loginMessage" label="消息内容" min-width="180" />
        <el-table-column prop="loginTime" label="登录时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.loginTime, 'yyyy-MM-dd HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="onDelete(scope.$index, scope.row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        class="pagination"
        :page-sizes="[30, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </dw-page-warpper>
</template>
<script setup lang="ts">
import { h, markRaw, onMounted, reactive, ref } from 'vue';

import { formatDate } from '@/utils/func';
import { dwHttp } from '@/utils/http';
import { ElMessageBox } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
defineOptions({
  name: 'SysLoginLog',
});

const props = defineProps({
  //初始化加载数据
  initedLoad: {
    type: Boolean,
    default: true,
  },
  selection: {
    type: Boolean,
    default: true,
  },
  showRowNum: {
    type: Boolean,
    default: true,
  },
});
const searchFormData = reactive({
  keyword: '',
});

const loginLogTableRef = ref();

const currentPage = ref<number>(1);
const pageSize = ref<number>(30);
const total = ref<number>(0);

const handleSizeChange = (val: number) => {
  loadData();
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  loadData();
};
const onSearch = () => {
  loadData();
};
const onDeleteList = () => {
  const idList: string[] = [];
  const selectionRows = loginLogTableRef.value.getSelectionRows();
  for (let i = 0; i < selectionRows.length; i++) {
    const row = selectionRows[i];
    idList.push(row.id);
  }

  ElMessageBox({
    title: '询问',
    message: h('p', null, [h('span', null, '确认删除当前选中的'), h('span', { style: 'color: red' }, `${idList.length}条`), h('span', null, '记录信息?')]),
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showCancelButton: true,
    icon: markRaw(QuestionFilled),
    type: 'warning',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        //调用删除接口
        if (action === 'confirm') {
          dwHttp({
            url: `/admin-api/log/login/log/list`,
            data: idList,
            method: 'delete',
          }).then((res) => {
            loadData();
          });
        }
      }
      done();
    },
  });
};

interface ILoginLog {
  id: string;
  loginLogName: string;
  loginLogMemo: string;
  sortNo: number;
}

const tableData = ref<ILoginLog[]>([]);

onMounted(() => {
  if (props.initedLoad) {
    loadData();
  }
});

const loadData = () => {
  dwHttp({
    url: '/admin-api/log/login/log/page/list',
    method: 'get',
    params: {
      keyword: searchFormData.keyword,
      pageSize: pageSize.value,
      currentPage: currentPage.value,
    },
    isSuccessTip: false,
  }).then((res) => {
    const { data } = res;
    const result = data as unknown as { totalRow: number; records: Array<unknown> };
    total.value = result.totalRow as number;
    tableData.value = result.records as unknown as ILoginLog[];
  });
};

const onDelete = (index: number, row: ILoginLog) => {
  ElMessageBox({
    title: '询问',
    message: h('p', null, [h('span', null, '确认删除'), h('span', null, '当前记录信息?')]),
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showCancelButton: true,
    icon: markRaw(QuestionFilled),
    type: 'warning',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        const id = row.id;
        dwHttp({
          url: `/admin-api/log/login/log/${id}`,
          method: 'delete',
        }).then((res) => {
          console.log(res);
          loadData();
        });
      }
      done();
    },
  });
};
</script>
<style lang="scss" scoped>
.dw-condition-warpper {
  padding-top: 10px;
  padding-left: 20px;
  padding-right: 20px;
  :deep(.el-form-item) {
    margin: 8px 2px;
  }
}

.dw-toolbar-warpper {
  padding-bottom: 10px;
  padding-left: 20px;
  padding-right: 20px;
}
.dw-data-warpper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: calc(100% - 100px);
}

.dw-full {
  width: 100%;
  height: 100%;
}
.pagination {
  margin: 5px 0;
}
</style>
